#!/bin/bash

# 定义 Java 程序的路径和名称
JAR_FOLDER="/mydata/jars/metahuman/admin"
JAR_NAME="metahuman-admin.jar"
JAR_PATH="$JAR_FOLDER/$JAR_NAME"
LOG_FILE="$JAR_FOLDER/metahuman-admin.log"
APPLICATION_YML="$JAR_FOLDER/application.yml"

# 检查 Java 运行环境是否可用
java -version >/dev/null 2>&1
if [ $? -ne 0 ]; then
  echo "Java is not installed or not in the PATH."
  exit 1
fi

# 检查是否已经启动了同一个 Java JAR 程序
PID=$(pgrep -f "$JAR_NAME")

# 如果程序正在运行，则关闭它
if [ -n "$PID" ]; then
  echo "Stopping the application with PID: $PID"
  kill "$PID"

  # 等待一段时间确保进程已经关闭
  TIMEOUT=10
  while [ $TIMEOUT -gt 0 ]; do
    if ! pgrep -f "$JAR_NAME" >/dev/null 2>&1; then
      echo "Application stopped successfully."
      break
    fi
    sleep 1
    ((TIMEOUT--))
  done

  if [ $TIMEOUT -eq 0 ]; then
    echo "Application did not stop gracefully, force stopping..."
    kill -9 "$PID"
  fi
fi

# 启动 Java JAR 程序
echo "Starting the application..."
nohup java -jar "$JAR_PATH" --spring.config.location="$APPLICATION_YML" >>"$LOG_FILE" 2>&1 &
echo "Application started successfully."
